﻿#region Using

using System.Threading.Tasks;

using Common.Base;

using ServerApplication.Enums;
using ServerApplication.Interfaces;
using ServerApplication.Networking;

#endregion

namespace ServerApplication
{
    public class MatchmakingManager : ICoreToMatchmakingManager
    {
        private const int PlayerCount = 2;

        private readonly IMatchmakingManagerToCore core;

        private readonly RemovableQueue<ServerPlayer> waitingQueue;

        public MatchmakingManager(IMatchmakingManagerToCore core)
        {
            this.waitingQueue = new RemovableQueue<ServerPlayer>();
            this.core = core;
        }

        public bool TryCancelMatchmaking(ServerPlayer player)
        {
            lock (this.waitingQueue)
            {
                if (!this.waitingQueue.Contains(player))
                {
                    return false;
                }

                this.waitingQueue.Remove(player);
                return true;
            }
        }

        public bool TryEnqueue(ServerPlayer player)
        {
            lock (this.waitingQueue)
            {
                if (this.waitingQueue.Contains(player))
                {
                    return false;
                }

                this.waitingQueue.Enqueue(player);

                new Task(this.CheckQueue).Start();

                return true;
            }
        }

        private void CheckQueue()
        {
            lock (this.waitingQueue)
            {
                this.waitingQueue.RemoveAll(x => x.ServerPlayerState == ServerPlayerState.Disconnected);

                if (this.waitingQueue.Count >= PlayerCount)
                {
                    this.core.WorkWithMatchedPlayers(this.waitingQueue.Take(PlayerCount));
                }
            }
        }
    }
}